<?php Workerman\Protocols\Http::sessionStart(); $G_MODEL_NAME = basename(__FILE__,'.js.php'); $G_MODEL_URL = $_SESSION["MES_WEB_URL"].'/'. $G_MODEL_NAME; ?>
<?php $access_token = $_SESSION["ACCESS_TOKEN"];?>
var authority_cache = {};
var oTable_config = "";	// 模块表对象
var oTable = "";	// 模块表对象
oTable = create_table();


// 右键菜单 - 提交  L1
$('#<?php echo $G_MODEL_NAME; ?>_form').validate({
	submitHandler:function(form){  
		//保存/修改
		var action = "";
		if($('[name="mod_groups_input_id"]').val()==""){
			//如果ID为空，新建一个记录
			action = "add";
		}else{
			//ID不为空，保存旧记录
			action = "edit";
		}
		var stat = 0;
		if($('[name="mod_groups_input_stat"]').is(':checked')){
			stat = 1;
		}
		ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{
			action:action,
			id:$('[name="mod_groups_input_id"]').val(),
			name:$('[name="mod_groups_input_name"]').val(),
			class:$('[name="mod_groups_input_class"]').val(),
			stat:stat,
			note:$('[name="mod_groups_input_note"]').val()
		},access_token:"<?php echo $access_token?>"},function(result){
			var result = JSON.parse(result);
			result = result["rtval"];
			if(result=="done"){
				//刷新数据
				oTable.ajax.reload( function ( json ) {
				});
				$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('hide');
			}else{
				alert(result);
			}
		})
		return false;
	},
	 rules: {
		 mod_groups_input_name: {
			 required: true,
			 minlength: 3
		 },
		 mod_groups_input_class: {
			 required: true,
			 minlength: 1
		 }
	 }
});
function analysis_cache(){
	let authority=[] ,	authority_class=[];
	Object.keys(authority_cache).some((module,v)=>{
		if(!authority_cache[module].display){
			authority_class.push(module);
		}
		let buttons = authority_cache[module].buttons;
		// log(module,buttons);
		Object.keys(buttons).some((btn,v)=>{
			if(!buttons[btn]){
				authority.push(btn);
			}
		});
	}); 
	return {
		"authority" : authority,
		"authority_class" : authority_class,
	};
}


//编辑资源 - 提交  L2
$('#<?php echo $G_MODEL_NAME; ?>_form_config').validate({
	submitHandler:function(form){
		let group_id = oTable.rows(['.selected']).data()[0][0];	//	获取组角色id
		let obj = analysis_cache();
		let authority = obj.authority;
		let authority_class = obj.authority_class;
		//保存
		ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{
			action:"groups_config_edit",
			id:group_id,
			authority:JSON.stringify(authority),
			authority_class:JSON.stringify(authority_class)
		},access_token:"<?php echo $access_token?>"},function(result){
			var result = JSON.parse(result);
			result = result["rtval"];
			if(result=="done"){
				//刷新数据
				$('#dlg_<?php echo $G_MODEL_NAME; ?>_config').modal('hide');
			}else{
				alert(result);
			}
		})
		return false;
	}
});

/*点击事件 start */
//右上角菜单按键
$(".mod_btn_<?php echo $G_MODEL_NAME; ?>").on("click", function(e){
	mod_fun_action($(this).attr("data-tap"));
});

//点击请求+渲染UI
$('#<?php echo $G_MODEL_NAME; ?>_list_config').on( 'click', 'tr td.details-control', function (){
	var tr = $(this).closest('tr');
	var id = oTable_config.row(tr).data().id;
	let data = array_obj_filter("id",id);
	init_edit_table(id,tr,data);
});

//全选按钮
$('#groups_all_checked').click(function(){
	var flage = $(this).is(":checked");
	$('#dlg_<?php echo $G_MODEL_NAME; ?>_config .moduel_check').prop("checked",flage);
	update_authority_cache('all',flage);
});
/*点击事件 end*/


/*初始化成员表*/
function create_table(){
	if(oTable){oTable.ajax.reload();return oTable;}
	return $('#<?php echo $G_MODEL_NAME; ?>_list').DataTable({
		"ajax": {
			url:"<?php echo $G_MODEL_URL;?>",
			beforeSend: function (request) {
				request.setRequestHeader("access_token","<?php echo $access_token?>");
			},
			"dataSrc": function ( json ) {
				check_ajax_request(json);
				return json["rtval"]["data"];
			}
		},
		"deferRender": true,
		"iDisplayLength": 25,
		columnDefs:[{
			targets: 6,
			render: function (data, type, row, meta) {
				return '<span class="label label-primary" style="cursor:pointer" onclick="do_module_config(' + row[0] + ', \'' + encodeURI(row[6]) + '\',\'' + encodeURI(row[7]) + '\');"> 编辑资源 </span>';
			}
		}],
		"destroy":true,
		"oLanguage": {
			"sLengthMenu": "每页显示 _MENU_ 条记录",	
			"sZeroRecords": "抱歉， 没有找到",
			"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			"sInfoEmpty": "没有数据",
			"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
			"sZeroRecords": "没有检索到数据",
			"sSearch": "搜索:",
			"oPaginate": {
				"sFirst": "首页",
				"sPrevious": "前一页",
				"sNext": "后一页",
				"sLast": "尾页"
			}
		},

		"fnRowCallback": function(nRow) {
			//右键回调
			$(nRow).on('mousedown',
			function(e) {
				
				if (e.button == 2) {
					if ($(this).hasClass('selected')) {
						//$(this).removeClass('selected');
					} else {
						oTable.$('tr.selected').removeClass('selected');
						$(this).addClass('selected');
					}
					// //console.log($(this));
						
					
					doDynamicMenu(0, {
							x: e.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft + 5,
							y: e.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
					});
					// return false;
				} 
				
				if(e.button != 2){
					if ($(this).hasClass('selected')) {
						//$(this).removeClass('selected');
					} else {
						
						oTable.$('tr.selected').removeClass('selected');
						$(this).addClass('selected');
					}
				}
				//判断是默认用户
				if(oTable.row($(nRow)).data()[0]==1){
					oTable.$('tr.selected').removeClass('selected');	
				}
				// return true;
			});
		},
		dom: '<"html5buttons"B>lTfgitp',
		buttons: [{
			extend: 'copy'
		},
		{
			extend: 'csv'
		},
		{
			extend: 'excel',
			title: 'ExcelFile'
		},
		{
			extend: 'pdf',
			title: 'PDFFile'
		},

		{
			extend: 'print',
			customize: function(win) {
				$(win.document.body).addClass('white-bg');
				$(win.document.body).css('font-size', '10px');

				$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
			}
		}]
	});
}


// 在模块表数据找到满足某个条件的值
function array_obj_filter(key,value){
	let index = null ;
	let arr = Array.from(oTable_config.data());
	arr.some((v,k)=>{
		if(v[key]===value){
			index = k;
			return true;
		}
	});
	let data = {
		"code":arr[index]["code"],
		"elements":arr[index]["elements"],
		"elemtext":arr[index]["elemtext"],
	}; 

	if(index === null)return index;
	else return data;
}


// 生成+新行的 html
function format ( d ) {
	var code = d.code;
	var elems = JSON.parse(d.elements);
	var elemtext = d.elemtext.split(",");
	var html = '';
	var non_control=0;

	for(i of elemtext){
		if(i.replace(/\s+/g,"")!=""){
			non_control++;
		}
	}

	if(non_control==0){
		var tip= "此模块没有可控制的按钮";
		html = '<div class="row" style="margin-right:20px;color:#42c23f">' +
							   '<span class="text-center col-md-12"><b>' +
							   '' + tip +
							   '</b></span>' +
							   '</div>';
	}else{
		for(i in elemtext){
			if(elemtext[i].replace(/\s+/g,"")!="" && elems[i]!=undefined && elemtext[i]!=undefined){
				html +=  '<div class="checkbox checkbox-primary" style="margin-right:20px;">' +
							   '<input type="checkbox" module="'+code+'" onclick="button_display_click(this)" name="mod_groups_config_elements" checked data-tap="' + elems[i] + '">' +
							   '<label for="'+elems[i]+'">' +
							   '' + elemtext[i] +
							   '</label>' +
							   '</div>';	
			}
			
		}
	}
	return html;
}


// 单击勾选按钮并更新缓存数据
function button_display_click(that){
	let is_check = $(that).prop('checked');
	let code = $(that).attr('module');
	let element = $(that).attr('data-tap');
	update_authority_cache("single_button", [code,element,is_check] );
}


//点击+示下一行按钮数据
function init_edit_table(id,tr,result){
	// log(tr,result);
	if(!result || !Object.keys(result).length){
		alert('无数据');return;
	}
	var a =  format ( result );
	var row = oTable_config.row(tr);
	row.child(a).show();
	tr.next().hide();

	if ( tr.hasClass( 'details' ) ) {
		tr.removeClass( 'details' );
		tr.next().hide();
	}
	else {
		tr.addClass( 'details' );
		tr.next().show();
		// 按authority_cache缓存内容取消勾选
		let code = result.code,
			buttons = authority_cache[code].buttons;
			
		tr.next().find("input").each(function(){
			var tap= $(this).attr("data-tap");
			if(!buttons[tap]){
				$('[data-tap="'+tap+'"]').removeAttr("checked");
			}
		});
	}
}

//点击编辑资源
function do_module_config(id){
	refresh_config_table(id);
	$('#dlg_<?php echo $G_MODEL_NAME; ?>_config').modal('show');
}


// 调用refresh_modules.php文件对模块进行刷新
function use_refresh_modules(){
	
	ajax_request({url:"<?php echo $_SESSION['MES_WEB_URL'];?>/refresh_modules",type:"POST",dataType:"TEXT",data:{action:"refresh_modules"},access_token:"<?php echo $access_token?>"},function(result){
		var result = JSON.parse(result);
		result = result["rtval"];
		swal('模块已刷新','','success');
		// 重新载入子页面
		$('a.mod_settings_groups').click();
	})
}

// 创建/渲染[模块表]数据 
// return oTable_config
// 获取 hf_mes_modules 参数 和 hf_mes_groups 中模块对比, 存在的模块置为不勾选 
function refresh_config_table(id){
	/*初始化编辑表格*/
	if(oTable_config){
		oTable_config.settings()[0].ajax.data = {"id": id, "action": "get_module_info"};
		oTable_config.ajax.reload(()=>{
			update_authority_cache();
		});return oTable_config;
	}
	oTable_config = $('#<?php echo $G_MODEL_NAME; ?>_list_config').DataTable({
		"ajax": {
			"url":"<?php echo $G_MODEL_URL;?>",
			"type":"post",
			"data": {
				"id":id,
				"action": "get_module_info"
			},
			"beforeSend": function (request) {
				request.setRequestHeader("access_token","<?php echo $access_token?>");
			},
			"dataSrc": function ( json ) {
				check_ajax_request(json);
				return json["rtval"]["data"];
			}
		},
		"scrollX": false,
		"autoWidth":false,
		"destroy":true,
		"iDisplayLength": 100,
		"deferRender": true,
		"columns": [
			{
				"class":	"details-control",
				"orderable":      false,
				"data":           null,
				"defaultContent": "",
			},
			{	"data": "id" ,},
			{ "data": "name", },
			{"data": "code",},
			{ "data": "class",},
			{"data": null,}
		],
		"columnDefs":[{
			"orderable":      false,
			"data":"code",
			"targets": 5,
			"render": function (data,type,row,meta) {
				var code = data["code"];
				var module_display = data["module_display"];
				module_display = module_display?"checked":'';
				return '<input type="checkbox"  style="cursor:pointer" class="checkbox checkbox-primary moduel_check" '+ module_display +'  name='+code+'>';
			}
		}],
		"fnRowCallback": function(nRow) {
			// log(2);
			$(nRow).on('mousedown',
			function(e) {
				if (e.button == 2) {
					if ($(this).hasClass('selected')) {
					} else {
						oTable_config.$('tr.selected').removeClass('selected');
						$(this).addClass('selected');
					}
					return false;
				} else {
					if ($(this).hasClass('selected')) {
					} else {
						oTable_config.$('tr.selected').removeClass('selected');
						$(this).addClass('selected');
					}
				}
				return true;
			});
		},
		"fnInitComplete": function(settings, json ) {
			update_authority_cache();
			//单击模块
			$("#<?php echo $G_MODEL_NAME; ?>_list_config tbody").on("click",".moduel_check",function(){
				var code= $(this).closest("tr").find("td").eq(3).html();
				var flage = $(this).is(":checked");
				let tmp_o = {};
				tmp_o[code] = flage;
				update_authority_cache('single_module',tmp_o);
			});
		},
		//datatable数据变化时回调
		"fnInfoCallback":function(oSettings, iStart, iEnd, iMax, iTotal, sPre){
			// 当前页面全被选中则勾选全选按钮
			var inp_status = true;
			$('#groups_list_config tbody').find("[type='checkbox']").each(function(){		
				inp_status = inp_status  &&  ($(this).is(":checked")==true);
			});
			
			if(inp_status){
				$("#groups_all_checked").prop("checked","checked");
			}else{
				$("#groups_all_checked").prop("checked","");
			}
		},
		"oLanguage": {
			"sLengthMenu": "每页显示 _MENU_ 条记录",
			"sZeroRecords": "抱歉， 没有找到",
			"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			"sInfoEmpty": "没有数据",
			"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
			"sZeroRecords": "没有检索到数据",
			"sSearch": "搜索:",
			"oPaginate": {
				"sFirst": "首页",
				"sPrevious": "前一页",
				"sNext": "后一页",
				"sLast": "尾页"
			}
		},
		dom: '<"html5buttons"B>lTfgitp',
		buttons: []
	});
	return oTable_config;
}


// 初始化/更新权限数据缓存
function update_authority_cache(type='init',param=""){
	if(type==='init'){		// 编辑资源调用一次
		let m_json = Array.from(oTable_config.data());
		let is_init = false ;
		if(!Object.keys(authority_cache).length){is_init=true}
		m_json.map((v)=>{
			let code = v.code, 
				module_display = v.module_display ,
				element_display = v.element_display ,
				elements = v.elements;
			elements = typeof(elements)==="string"?JSON.parse(elements):elements;
			let buttons = {} ;
			elements.map((vv,kk)=>{
				buttons[vv]=element_display[kk];
			});
			if( is_init || authority_cache[code]===undefined )authority_cache[code]= {} ; 
			authority_cache[code].display = module_display ,
			authority_cache[code].buttons= buttons;
		});
	}else if(type==='all'){ 		// 	更新全部模块, 第二个参数为bool[true/false]
		Object.keys(authority_cache).map((key,v)=>{
			authority_cache[key].display = param;
		});
	}else if(type==='single_module'){		//	 更新单个模块,第二个参数格式为 {module_name:[bool]}
		let module_name = Object.keys(param)[0];
		authority_cache[module_name].display = param[module_name];
	}else if(type==='single_button'){		//	 更新单个模块的按钮,第二个参数格式为 [module_name,button_name,[bool]] 
		authority_cache[param[0]].buttons[param[1]] = param[2] ;
	}
	// log(authority_cache);
}


//创建右键菜单
function doDynamicMenu(idx, pos) {
	if($("<div class='mod_menu_<?php echo $G_MODEL_NAME; ?>'/>")){
		$("<div class='mod_menu_<?php echo $G_MODEL_NAME; ?>'/>").remove();
	}
	var $mymenu = $("<div class='mod_menu_<?php echo $G_MODEL_NAME; ?>'/>");
	$("body").append($mymenu);
	var my_item="";
		$.contextMenu({
				// reposition: true,
				selector: '.mod_menu_<?php echo $G_MODEL_NAME; ?>',
				callback: function(key, options) {
					mod_fun_action(key);
				},
				items: {
					"add": {
						name: "添加",
						className: 'cps_groups_menu_btn_001'
					},
					"edit": {
						name: "修改",
						className: 'cps_groups_menu_btn_002'
					},
					"delete": {
						name: "删除",
						className: 'cps_groups_menu_btn_003',
					},
					"sep1": "---------",
					"refresh": {
						name: "刷新",
						className: 'cps_groups_menu_btn_004'
					}
				}

		});
	
	$(".mod_menu_<?php echo $G_MODEL_NAME; ?>").contextMenu(pos);
}


function mod_fun_action(key){
	if(key=="add"){
		$('[name="mod_groups_input_id"]').val("");
		$('[name="mod_groups_input_name"]').val("");
		$('[name="mod_groups_input_class"]').val("");
		$('[name="mod_groups_input_note"]').val("");
		$('[name="mod_groups_input_stat"]').removeAttr("checked");
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('show');
		return;
	}
	
	if(key=="edit"){
		var o = oTable.row('.selected');
		// 判断没有选中行
		if(typeof(o.data()) == "undefined"){
			return;
		}
		$('[name="mod_groups_input_id"]').val(o.data()[0]);
		$('[name="mod_groups_input_name"]').val(o.data()[1]);
		$('[name="mod_groups_input_class"]').val(o.data()[2]);
		$('[name="mod_groups_input_note"]').val(o.data()[3]);
		if(o.data()[4]=="开启"){
			$('[name="mod_groups_input_stat"]').prop("checked","checked");
		}else{
			$('[name="mod_groups_input_stat"]').removeAttr("checked");
		}
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('show');
		return;
	}
	
	if(key=="delete"){
		var o = oTable.row('.selected');
		// 判断没有选中行
		if(typeof(o.data()) == "undefined"){
			swal("提示","默认用户不可删除","warning");
			return;
		}//console.log(0);
		swal({ 
          title: '确定删除该记录', 
          text: '如果删除该记录,数据将无法恢复!', 
          type: 'warning',
          showCancelButton: true, 
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: '删除！',
          cancelButtonText: '取消！', 
        }).then(function(result){
            if (result.value) {
               // 删除当前选择行
				var id = o.data()[0];
				ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"delete",id:id},access_token:"<?php echo $access_token?>"},function(result){
                    var result = JSON.parse(result);
                    result = result["rtval"];
                    if(result=="done"){
                        //刷新数据
                        oTable.ajax.reload();
                        swal(
                            '已经删除!',
                            '该记录已被成功删除',
                            'success'
                        );
                    }else{
                        oTable.ajax.reload();
                        swal(
                            '无法删除!',
                            result,
                            'error'
                        );
                        
                    }
                })
            } 
        })				
		return;
	}
	
	if(key=="refresh"){
		// 刷新数据
		oTable.ajax.reload();
		return;
	}
	
	return;
}